<script>
import {defineComponent} from 'vue'
import {FileUtils} from "../../utils/FileUtils.ts";
import {imgTypeOptions} from "../../config/options.ts";
import {checkFile, deleteById, upload} from "../../api/file.js";
import {FastFileUtils} from "../../utils/FastFileUtils.ts";
import {PathUtils} from "../../utils/PathUtils.ts";
import {getDownloadUrl} from "../../api/nosecurity/file.js";
import {ElMessageBox} from "element-plus";

export default defineComponent({
  name: "FastImgUpload",
  props: {
    limit: {
      type: Number,
      default: 1,
    },
    modelValue: {
      type:Array,
      default: ()=>[]
    },
    disabled: {
      type:Boolean,
      default: false
    },
    disabledDel: {
      type:Boolean,
      default: false
    },
    accept: {
      type:String,
      default: ()=>{
        return imgTypeOptions.join(',')
      }
    },
  },
  created() {
    if(!this.modelValue || !this.modelValue.length) {
      this.asyncModelValue = []
    }
  },
  computed: {
    asyncModelValue: {
      get() {
        return this.modelValue
      },
      set(val = []){
        this.$emit('update:modelValue',val)
      }
    },
    showModelValue() {
      if(this.modelValue && this.modelValue.length) {
        return this.modelValue.map(i=>{
          return i
        })
      }
      return []
    }
  },
  methods: {
    handlePictureCardPreview(daiWeiBaiFile) {
      this.$emit('handlePictureCardPreview',daiWeiBaiFile)
    },
    async handleRemove(daiWeiBaiFile) {
      await ElMessageBox.confirm('确定删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: "warning",
      })
      let findIndex = this.asyncModelValue.find(i => i === daiWeiBaiFile)
      if (findIndex > -1) {
        this.asyncModelValue.splice(findIndex, 1)
      }
      deleteById(daiWeiBaiFile.fileId)
      this.$emit('handleRemove', daiWeiBaiFile)
    },
    async httpRequest(options) {
      let file = options.file
      let fileName = file.name
      let ext = PathUtils.extName(file.name)
      let isImg = imgTypeOptions.includes(ext)
      if (!isImg) {
        this.$modal.msgError(`只能上传${imgTypeOptions.join(',')}文件!`);
        return
      }
      let md5 = await FileUtils.fileToMd5(file)
      const checkForm= new FormData()
      checkForm.append('md5',md5)
      checkForm.append('fileName',fileName)
      let checkData = await checkFile(checkForm)
      if(checkData.data) {
        this.fileAndUrlPush(checkData.data)
      } else {
        const form = new FormData()
        form.append('file',file)
        form.append('md5',md5)
        let formData = await upload(form)
        if(formData.data) {
          this.fileAndUrlPush(formData.data)
        }
      }
    },
    fileAndUrlPush(data) {
      let url = getDownloadUrl(FastFileUtils.fileToSaveFileNameT(data))
      this.asyncModelValue.push({
        fileId: data.id,
        url,
        name: data.fileName
      })
      this.$nextTick(()=>{
        this.$emit('success')
      })
    },
  }
})
</script>

<template>
  <el-upload action="#"
             :file-list="showModelValue"
             :limit="limit"
             list-type="picture-card"
             class="FastImgUpload"
             :class="{hide: asyncModelValue.length>=limit}"
             :http-request="httpRequest"
             :accept="accept"
             :auto-upload="true">
    <el-icon><Plus /></el-icon>
    <template #file="{file}">
      <div>
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
        <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="handlePictureCardPreview(file)"
          >
            <el-icon><zoom-in /></el-icon>
          </span>
          <span
            v-if="!disabled && !disabledDel"
            class="el-upload-list__item-delete"
            @click="handleRemove(file)"
          >
            <el-icon><Delete /></el-icon>
          </span>
        </span>
      </div>
    </template>
  </el-upload>
</template>

<style scoped lang="scss">
.FastImgUpload{
  &.hide{
    ::v-deep{
      .el-upload{
        display: none;
      }
    }
  }
  ::v-deep{

  }
}
</style>
